<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="驱动名称" prop="driverName">
        <el-input
          v-model="queryParams.driverName"
          placeholder="请输入驱动名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="primary" plain @click="openForm('create')">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <!-- <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['mqtt:device-driver:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <!-- <el-table-column label="设备ID" align="center" prop="deviceId" /> -->
      <el-table-column
        label="通讯口"
        align="center"
        prop="commPortId"
        :formatter="formatCommPort"
      />
      <el-table-column label="驱动名称" align="center" prop="driverName" />
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="设备地址" align="center" prop="deviceAddress" />
      <!-- <el-table-column label="最小采集时间(ms)" align="center" prop="minCollectTime" />
      <el-table-column label="通讯等待时间(ms)" align="center" prop="commWaitTime" /> -->
      <!-- <el-table-column label="16位整型" align="center" prop="int16AddressRange">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MQTT_DEVICE_INT16" :value="scope.row.int16AddressRange" />
        </template>
      </el-table-column>
      <el-table-column label="32/64位整型" align="center" prop=" int3264AddressRan">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MQTT_DEVICE_INT3264" :value="scope.row.int3264AddressRan" />
        </template>
      </el-table-column>
      <el-table-column label="32/64位浮点型" align="center" prop="float3264AddressRange">
        <template #default="scope">
          <dict-tag
            :type="DICT_TYPE.MQTT_DEVICE_FLOAT3264"
            :value="scope.row.float3264AddressRange"
          />
        </template>
      </el-table-column>
      <el-table-column label="字符串字节序" align="center" prop="stringByteOrder">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MQTT_DEVICE_STRINGBYTE" :value="scope.row.stringByteOrder" />
        </template>
      </el-table-column>
      <el-table-column label="字符串编码" align="center" prop="stringEncoding">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MQTT_DEVICE_ENCODE" :value="scope.row.stringEncoding" />
        </template>
      </el-table-column>
      <el-table-column label="分块采集方式" align="center" prop="blockCollectMode">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MQTT_DEVICE_BLOCK" :value="scope.row.blockCollectMode" />
        </template>
      </el-table-column>
      <el-table-column label="4区16位写功能码" align="center" prop="codeWrite" />
      <el-table-column
        label="通讯间隔时间(ms)'"
        align="center"
        prop="commIntervalTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      /> -->
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DeviceDriverForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DeviceDriverApi, DeviceDriverVO } from '@/api/mqtt/devicedriver'
import DeviceDriverForm from './DeviceDriverForm.vue'
import { CommPortApi } from '@/api/mqtt/commport'

/** 设备驱动 列表 */
defineOptions({ name: 'DeviceDriver' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<DeviceDriverVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceId: undefined,
  commPortId: undefined,
  driverName: undefined,
  brand: undefined,
  model: undefined,
  deviceAddress: undefined,
  minCollectTime: [],
  commWaitTime: [],
  int16AddressRange: undefined,
  int3264AddressRan: undefined,
  float3264AddressRange: undefined,
  stringByteOrder: undefined,
  stringEncoding: undefined,
  blockCollectMode: undefined,
  codeWrite: undefined,
  commIntervalTime: [],
  description: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const commPortList = ref<any[]>([]) // 通讯口列表
const props = defineProps<{
  device: number
}>()
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DeviceDriverApi.getDeviceDriverPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number, device?: any) => {
  formRef.value.open(type, id, props.device)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DeviceDriverApi.deleteDeviceDriver(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DeviceDriverApi.exportDeviceDriver(queryParams)
    download.excel(data, '设备驱动.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const formatCommPort = (row) => {
  const commPortId = Array.isArray(row.commPortId)
    ? row.commPortId
    : row.commPortId
    ? [row.commPortId.toString()]
    : []
  console.log('commPortId------>>>>>>', commPortId)
  const commPortNames = commPortId
    .map((id) => {
      const commPort = commPortList.value.find((item) => item.id.toString() === id.toString())
      return commPort?.portName || ''
    })
    .filter(Boolean)
  return commPortNames.join(',') || ''
}
/** 初始化 **/
onMounted(() => {
  console.log('onMounted')
  getList()
  CommPortApi.getCommPortPage({ page: 1, size: 100 })
    .then((res) => {
      commPortList.value = res.list
      // console.log('commPortList', commPortList.value)
    })
    .catch((err) => {
      console.log('获取通讯口列表失败', err)
    })
})
</script>
